#include <network\streamingServer.h>

#include <app\states\cacheState.h>

streamingServer::streamingServer(boost::asio::io_service& io_service, short port)
    : io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), port)) {
  streamingConnection* new_connection = new streamingConnection(io_service_);
  acceptor_.async_accept(new_connection->socket(),
      boost::bind(&streamingServer::handle_accept, this, new_connection,
        boost::asio::placeholders::error));

  #ifdef DEBUG_INFO
  cerr << "start handling new connections" << endl;
  #endif
}

void 
streamingServer::handle_accept(streamingConnection* new_connection, const boost::system::error_code& error) {
  if (!error)
  {
    cacheState *cstate = GET_STATE(cacheState, new_connection);
    cstate->setCacheDir("D:\\streamingserverdb");

    #ifdef DEBUG_INFO
    cerr << "Handling incoming connection" << endl;
    #endif

    new_connection->start();
    new_connection = new streamingConnection(io_service_);
    acceptor_.async_accept(new_connection->socket(),
        boost::bind(&streamingServer::handle_accept, this, new_connection,
          boost::asio::placeholders::error));
  }
  else
  {
    #ifdef DEBUG_INFO
    cerr << "Handle accept error" << endl;
    #endif
    delete new_connection;
  }
}
